package com.app.service.Impl;

import com.app.entity.po.HuibenHomework;
import com.app.entity.po.HuibenHomeworkClass;
import com.app.mapper.HuibenHomeworkMapper;
import com.app.mapper.HuibenHomeworkBookBindMapper;
import com.app.mapper.HuibenHomeworkClassMapper;
import com.app.mapper.HuibenHomeworkUserMapper;
import com.app.service.IHuibenHomeworkService;
import com.app.vo.HomeworkDetailVO;
import com.app.vo.HomeworkInfoVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.Collections;
import com.app.vo.HomeworkUserVO;
import com.app.mapper.HuibenBookMapper;
import com.app.vo.BookVO;
import com.app.vo.BookInfoVO;
import java.util.HashMap;
import com.app.entity.po.HuibenBook;
import com.app.vo.CreateHomeworkDTO;
import com.app.mapper.HuibenClassMemberMapper;
import org.springframework.transaction.annotation.Transactional;
import com.app.entity.po.HuibenHomeworkBookBind;

/**
 * <p>
 * 作业表 服务实现类
 * </p>
 *
 * @author lizi
 * @since 2025-07-29
 */
@Service
public class HuibenHomeworkServiceImpl extends ServiceImpl<HuibenHomeworkMapper, HuibenHomework> implements IHuibenHomeworkService {

    @Autowired
    private HuibenHomeworkBookBindMapper homeworkBookBindMapper;
    
    @Autowired
    private HuibenHomeworkClassMapper homeworkClassMapper;
    @Autowired
    private HuibenHomeworkUserMapper homeworkUserMapper;
    @Autowired
    private HuibenBookMapper huibenBookMapper;
    @Autowired
    private HuibenClassMemberMapper huibenClassMemberMapper;

    // 获取作业详情
    @Override
    public HomeworkDetailVO getHomeworkDetail(Long homeworkId, Long classId) {
        // 查询作业基本信息
        HuibenHomework homework = this.getById(homeworkId);
        if (homework == null) {
            return null;
        }
        
        // 查询关联的书籍ID列表
        List<Long> bookIds = homeworkBookBindMapper.selectBookIdsByHomeworkId(homeworkId);
        
        // 查询关联的班级ID列表
        List<Long> classIds = homeworkClassMapper.selectClassIdsByHomeworkId(homeworkId);
        
        // 查询统计信息（根据classId和homeworkId）
        Map<String, Object> stats = homeworkUserMapper.getHomeworkStats(homeworkId, classId);

        // 构建返回对象
        HomeworkDetailVO detailVO = new HomeworkDetailVO();
        detailVO.setHomeworkId(homework.getHomeworkId());
        detailVO.setTitle(homework.getTitle());
        detailVO.setDate(homework.getDate().toString());
        detailVO.setRequirement(homework.getRequirement());
        detailVO.setBooks(bookIds);
        detailVO.setClasses(classIds);
        detailVO.setCompletedCount(((Number)stats.get("completedCount")).intValue());
        detailVO.setTotalCount(((Number)stats.get("totalCount")).intValue());
        detailVO.setUncompletedCount(((Number)stats.get("uncompletedCount")).intValue());
        
        return detailVO;
    }

    /**
     * 转换用户数据为VO
     */
    // 获取班级下所有作业及完成人数（分页）
    @Override
    public List<HomeworkInfoVO> getHomeworkList(Long classId, Integer page, Integer pageSize) {
        // 1. 分页查作业ID和status
        Page<HuibenHomeworkClass> pageParam = new Page<>(page, pageSize);
        Page<HuibenHomeworkClass> classPage = homeworkClassMapper.selectPage(
            pageParam, new QueryWrapper<HuibenHomeworkClass>().eq("class_id", classId)
        );
        List<Long> homeworkIds = classPage.getRecords().stream()
            .map(HuibenHomeworkClass::getHomeworkId)
            .collect(Collectors.toList());

        if (homeworkIds.isEmpty()) {
            return Collections.emptyList();
        }

        // 2. 查作业基本信息
        List<HuibenHomework> homeworkList = baseMapper.selectByHomeworkIds(homeworkIds);

        // 3. 统计完成人数
        List<Map<String, Object>> finishedList = homeworkUserMapper.countFinishedByHomeworkIdsAndClassId(homeworkIds, classId);
        Map<Long, Integer> finishedMap = finishedList.stream()
            .collect(Collectors.toMap(
                m -> ((Number)m.get("homework_id")).longValue(),
                m -> ((Number)m.get("finished")).intValue()
            ));

        // 4. 创建homeworkId到homework的映射
        Map<Long, HuibenHomework> homeworkMap = homeworkList.stream()
            .collect(Collectors.toMap(HuibenHomework::getHomeworkId, h -> h));

        // 5. 封装VO并直接返回
        return classPage.getRecords().stream().map(classRecord -> {
            Long homeworkId = classRecord.getHomeworkId();
            HuibenHomework homework = homeworkMap.get(homeworkId);
            
            HomeworkInfoVO vo = new HomeworkInfoVO();
            vo.setHomeworkId(homeworkId);
            vo.setTitle(homework.getTitle());
            vo.setDate(homework.getDate().toString());
            vo.setFinished(finishedMap.getOrDefault(homeworkId, 0));
            vo.setStatus(classRecord.getStatus());
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * 获取已完成用户列表
     */
    @Override
    public List<HomeworkUserVO> getCompletedUsers(Long homeworkId, Long classId) {
        List<Map<String, Object>> userDataList = homeworkUserMapper.getCompletedUsers(homeworkId, classId);
        return userDataList.stream()
            .map(this::convertToHomeworkUserVO)
            .collect(Collectors.toList());
    }

    /**
     * 获取未完成用户列表
     */
    @Override
    public List<HomeworkUserVO> getUncompletedUsers(Long homeworkId, Long classId) {
        List<Map<String, Object>> userDataList = homeworkUserMapper.getUncompletedUsers(homeworkId, classId);
        return userDataList.stream()
            .map(this::convertToHomeworkUserVO)
            .collect(Collectors.toList());
    }

    /**
     * 转换用户数据为VO
     */
    private HomeworkUserVO convertToHomeworkUserVO(Map<String, Object> userData) {
        HomeworkUserVO vo = new HomeworkUserVO();
        // BigInt转Long
        vo.setUserId(Long.parseLong(userData.get("userId").toString()));
        vo.setNickname((String) userData.get("nickname"));
        vo.setAvatar((String) userData.get("avatar"));
        return vo;
    }

    /**
     * 根据书籍ID数组获取书籍详情
     */
    @Override
    public List<BookVO> getBookDetailByIds(List<Long> bookIds) {
        if (bookIds == null || bookIds.isEmpty()) {
            return Collections.emptyList();
        }
        
        List<HuibenBook> books = huibenBookMapper.selectByBookIds(bookIds);
        
        return books.stream().map(book -> {
            BookVO vo = new BookVO();
            vo.setId(book.getId());
            vo.setTitle(book.getTitle());
            vo.setCoverUrl(book.getCoverUrl());
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * 获取绘本列表（分页）
     */
    @Override
    public Map<String, Object> getBookList(Integer page, Integer pageSize, String keyword) {
        // 创建分页对象
        Page<HuibenBook> pageParam = new Page<>(page, pageSize);
        
        // 构建查询条件
        QueryWrapper<HuibenBook> queryWrapper = new QueryWrapper<>();
        if (keyword != null && !keyword.trim().isEmpty()) {
            queryWrapper.like("title", keyword.trim());
        }
        queryWrapper.orderByDesc("created_at");
        
        // 执行分页查询
        Page<HuibenBook> bookPage = huibenBookMapper.selectPage(pageParam, queryWrapper);
        
        // 转换为VO
        List<BookInfoVO> bookInfoList = bookPage.getRecords().stream().map(book -> {
            BookInfoVO vo = new BookInfoVO();
            vo.setId(book.getId());
            vo.setTitle(book.getTitle());
            vo.setCoverUrl(book.getCoverUrl());
            vo.setCreatedAt(book.getCreatedAt() != null ? book.getCreatedAt().toString() : null);
            return vo;
        }).collect(Collectors.toList());
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("list", bookInfoList);
        result.put("total", bookPage.getTotal());
        result.put("page", page);
        result.put("pageSize", pageSize);
        
        return result;
    }

    /**
     * 创建作业
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createHomework(CreateHomeworkDTO createHomeworkDTO) {
        //从security上下文获取当前登录用户ID
        Long id = SecurityFrameworkUtils.getLoginUserId();
        // 1. 创建作业基本信息
        HuibenHomework homework = new HuibenHomework();
        homework.setTitle(createHomeworkDTO.getTitle());
        homework.setDate(LocalDate.parse(createHomeworkDTO.getDate()));
        homework.setRequirement(createHomeworkDTO.getRequirement());
        homework.setCreatorId(id); // 这里需要从当前登录用户获取
        homework.setCreatedAt(LocalDateTime.now());

        
        // 保存作业
        this.save(homework);
        Long homeworkId = homework.getHomeworkId();
        
        // 2. 遍历书籍ID，添加到关联表
        if (createHomeworkDTO.getBooks() != null && !createHomeworkDTO.getBooks().isEmpty()) {
            for (Long bookId : createHomeworkDTO.getBooks()) {
                HuibenHomeworkBookBind bookBind = new HuibenHomeworkBookBind();
                bookBind.setHomeworkId(homeworkId);
                bookBind.setBookId(bookId);
                homeworkBookBindMapper.insert(bookBind);
            }
        }
        
        // 3. 遍历班级ID，添加到关联表并设置status为0
        if (createHomeworkDTO.getClasses() != null && !createHomeworkDTO.getClasses().isEmpty()) {
            for (Long classId : createHomeworkDTO.getClasses()) {
                // 添加到作业-班级关联表
                HuibenHomeworkClass classBind = new HuibenHomeworkClass();
                classBind.setHomeworkId(homeworkId);
                classBind.setClassId(classId);
                classBind.setStatus("0"); // 设置status为0
                homeworkClassMapper.insert(classBind);
                
                // 4. 查询该班级的所有用户ID
                List<Long> userIds = huibenClassMemberMapper.selectUserIdsByClassId(classId);
                
                // 5. 为每个用户创建作业-用户关联记录
                if (userIds != null && !userIds.isEmpty()) {
                    for (Long userId : userIds) {
                        // 这里需要创建HuibenHomeworkUser实体类
                        // 由于没有实体类，我们直接使用SQL插入
                        homeworkUserMapper.insertHomeworkUser(homeworkId, userId, classId, 0);
                    }
                }
            }
        }
        
        return homeworkId;
    }
}
